package com.landmesure.communication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.code.EntityType;
import com.landmesure.bluetoothchat.constant.Constant;
import com.landmesure.bluetoothchat.view.BluetoothFragment;
import com.code.CommandType;
import com.landmesure.core.TestMessage;
import com.util.NumberUtil;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import static android.content.ContentValues.TAG;
import static com.landmesure.bluetoothchat.constant.Constant.ADD_DECODE_OBJECT_TO_SERIVCE;
import static com.landmesure.bluetoothchat.constant.Constant.SET_ARGS_ERROR;
import static com.landmesure.bluetoothchat.constant.Constant.SET_ARGS_SUCCESS;
import static com.landmesure.bluetoothchat.view.BluetoothFragment.landCommunicationServiceInstance;
import static com.code.DataType.CODE_ERROR;
import static com.code.DataType.CODE_HISTROYDATA;
import static com.code.DataType.CODE_OBJECTDATA;
import static com.code.DataType.CODE_PARAM;
import static com.code.DataType.CODE_STATUSDATA;
import static com.code.DataType.CODE_STATUS_TESTDATA;
import static com.code.DataType.CODE_SUCCESS;
import static com.code.DataType.CODE_SUCCESS_QUERYDATA;
import static com.code.DataType.CODE_SUCCESS_TEST;
import static com.code.DataType.CODE_TESTDATA;

public class ReadBoardManager extends BaseManager {

    //是否设置参数
    public static boolean setArgs;
    //是否复位
    public static boolean reset;
    public static List<List<TestMessage>> allTestMessages = new ArrayList<>();


    public ReadBoardManager(Handler handler) {
        this.handler=handler;
    }

    /**
     * 通知Fragment
     */
    private void notifyFragment(String readMessage) {
        Message msg = new Message();
        Bundle data = new Bundle();
        data.putString("data", readMessage);
        msg.what = Constant.MESSAGE_READ;
        msg.setData(data);
        handler.sendMessage(msg);
    }

    @Override
    public void switchMessage(String ms) throws Exception {
        int dataType = getDataType(ms);
        String rcvMessage;
        switch (dataType) {
            case CODE_TESTDATA:
                break;
            case CODE_STATUSDATA:
                break;
            case CODE_SUCCESS:
                if (setArgs) {
                    Message msg = new Message();
                    msg.what = SET_ARGS_SUCCESS;
                    handler.sendMessage(msg);
                    SendMessageService sendMessageService = new SendMessageService();
                    sendMessageService.sendMessage(landCommunicationServiceInstance.getEntityType(), Constant.QUERY_PARAMETERS, landCommunicationServiceInstance.getCode(),null);
                }
                break;
            case CODE_PARAM:
                if (setArgs) {
                    rcvMessage = MonitorItemDecode.decodeParameter(ms, landCommunicationServiceInstance.getEntityType(), landCommunicationServiceInstance.getCode());
                    landCommunicationServiceInstance.getUfInstance().update(rcvMessage);
                }
            case CODE_OBJECTDATA:
                if (!setArgs) {
                    EntityType entityType = null;
                    try {
                        entityType = ReadBoardEngine.decode(ms);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (entityType != null) {
                        sendToBluetoothChat(entityType);
                    }
                }
                setArgs = false;
            case CODE_ERROR:
                if (setArgs) {
                    if (reset) {
                        Message msg = new Message();
                        msg.what = SET_ARGS_SUCCESS;
                        handler.sendMessage(msg);
                        reset = false;
                        setArgs = false;
                    } else {
                        Message msg = new Message();
                        msg.what = SET_ARGS_ERROR;
                        handler.sendMessage(msg);
                        setArgs = false;
                    }
                }
                break;
            case CODE_HISTROYDATA:
                break;
            case CODE_SUCCESS_QUERYDATA:
                BluetoothFragment.communicationType = CommandType.COMMAND_QUERY_OBJECT;
                break;
            case CODE_SUCCESS_TEST:
                processTestMessage(ms);
                break;
            case CODE_STATUS_TESTDATA:
                break;
            default:
                break;
        }
    }

    public void processRcvMessage(String readMessage) {
        CommunicationPlatform.deadlineTime=System.currentTimeMillis()+CommunicationPlatform.OVER_TIME;
        appendMessage(readMessage, totalMessage);
        notifyFragment(readMessage);
        processScodeForDecode();
    }



    private void processTestMessage(String ms) throws ParseException {
        List<TestMessage> testMessages;
        testMessages = MonitorItemDecode.decodeMonitorItem(ms);
        allTestMessages.add(testMessages);
        String tm = getTestMessages();
        if (null == tm) {
            landCommunicationServiceInstance.getUfInstance().update(testMessages.toString());
        } else {
            landCommunicationServiceInstance.getUfInstance().update(tm);
        }
    }

    private String getTestMessages() {
        double aSin = 0D;
        double bSin = 0D;
        boolean isSpecial = false;
        for (List<TestMessage> testMessages1 : allTestMessages) {
            for (TestMessage testMessage : testMessages1) {
                if (testMessage.getName().equals("A向倾角sin值")) {
                    isSpecial = true;
                    Log.i(TAG, "yuanA向倾角sin值: " + testMessage.getValue());
                    aSin += Double.parseDouble(testMessage.getValue());
                }
                if (testMessage.getName().equals("B向倾角sin值")) {
                    Log.i(TAG, "yuanB向倾角sin值: " + testMessage.getValue());
                    bSin += Double.parseDouble(testMessage.getValue());
                }
            }
        }
        if (isSpecial) {
            Map<String, Object> map = new TreeMap<>();
            double aV = aSin / allTestMessages.size();
            double bV = bSin / allTestMessages.size();
            Log.i(TAG, "yuanallTestMessages.size(): " + allTestMessages.size());
            Log.i(TAG, "yuanA向倾角sin值均值: " + aV);
            Log.i(TAG, "yuanB向倾角sin值均值: " + bV);
            map.put("测量次数", allTestMessages.size());
            map.put("A向倾角sin值均值", NumberUtil.decimalFormat(8).format(aV));
            map.put("B向倾角sin值均值", NumberUtil.decimalFormat(8).format(bV));
            map.put("倾斜度", NumberUtil.doubleToPercent(Math.sqrt(Math.pow(aV, 2.0) + Math.pow(bV, 2.0)), 2));
            return map.toString();
        } else {
            return null;
        }

    }


    private void sendToBluetoothChat(EntityType entityType) {
        Message msg = new Message();
        msg.obj = entityType;
        msg.what = ADD_DECODE_OBJECT_TO_SERIVCE;
        handler.sendMessage(msg);
    }
}
